package com.gdk.ksoft.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.dialog.OperatorMenu;
import com.gdk.ksoft.assembly.receiver.ExitAppReceiver;
import com.gdk.ksoft.assembly.service.ForegroundService;
import com.gdk.ksoft.assembly.service.LocationService;
import com.gdk.ksoft.assembly.utils.TaskUtils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.PhoneUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.common.constants.TaskConstant;
import com.gdk.ksoft.data.entry.tables.BankTable;
import com.gdk.ksoft.data.entry.tables.ContactorTable;
import com.gdk.ksoft.data.entry.tables.CustomerAreaTable;
import com.gdk.ksoft.data.entry.tables.CustomerDebtTable;
import com.gdk.ksoft.data.entry.tables.CustomerPriceTable;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.CustomerTypeTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.data.entry.tables.GoodsBrandTable;
import com.gdk.ksoft.data.entry.tables.GoodsGroupDetailTable;
import com.gdk.ksoft.data.entry.tables.GoodsGroupTable;
import com.gdk.ksoft.data.entry.tables.GoodsModuleTable;
import com.gdk.ksoft.data.entry.tables.GoodsTable;
import com.gdk.ksoft.data.entry.tables.PriceTable;
import com.gdk.ksoft.data.entry.tables.SaleBuyOtherCustomerTable;
import com.gdk.ksoft.data.entry.tables.SaleBuyOtherGiftTable;
import com.gdk.ksoft.data.entry.tables.SaleBuyOtherGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleBuyOtherLevelTable;
import com.gdk.ksoft.data.entry.tables.SaleBuyOtherTable;
import com.gdk.ksoft.data.entry.tables.SaleBuySelfCustomerTable;
import com.gdk.ksoft.data.entry.tables.SaleBuySelfGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleBuySelfLevelTable;
import com.gdk.ksoft.data.entry.tables.SaleBuySelfTable;
import com.gdk.ksoft.data.entry.tables.SaleGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleStatisticsTable;
import com.gdk.ksoft.data.entry.tables.SaleTable;
import com.gdk.ksoft.data.entry.tables.UnsoldGoodsTable;
import com.gdk.ksoft.ui.customers.NewCustomerActivity;
import com.gdk.ksoft.ui.logins.DownloadTableActivity;
import com.gdk.ksoft.ui.logins.LoginActivity;
import com.gdk.ksoft.ui.mores.FragmentMore;
import com.gdk.ksoft.ui.reporters.FragmentReports;
import com.gdk.ksoft.ui.works.FragmentWork;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnRadioGroupCheckedChange;
import com.zkc.helper.printer.Device;
import com.zkc.helper.printer.bt.BtService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * 主页面
 */
public class MainActivity extends FragmentActivity implements FragmentMore.OnExitListener{

    /**
     * 更新数据监听器
     */
    public interface OnUpdateListener{
        public void onExecuteUpdate();
    }

    /**
     * 上传数据监听器
     */
    public interface OnUploadListener{
        public void onExecuteUpload(ProgressValue progressValue);
    }

    public static BtService pl = null;//蓝牙打印机对象
    public static List<Device> deviceList = new ArrayList<>();//蓝牙数据集合
    public static boolean checkState = false;//蓝牙是否可用
    private Context context;//上下文对象

    @ViewInject(R.id.pmain_flHeader)private LinearLayout flHeader;//头部栏
    @ViewInject(R.id.pmain_txtUploadCount)private TextView txtUploadCount;//为上传的销售单数量

    private OperatorMenu operatorMenu;//侧栏操作菜单
    private FragmentWork fragmentWork;//工作页面
    private FragmentReports fragmentOrder;//订单页面
    private FragmentMore fragmentMore;//更多页面
    private long exitTime = 0;//退出的时间戳
    private int screenWidth = 0;//屏幕宽度
    private DbUtils dbUtils;//数据库操作对象
    private ExitAppReceiver exitAppReceiver;//退出应用数据通知

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewUtils.inject(this);
        context = MainActivity.this;
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        registeExitAppReceiver();//注册退出应用的通知
        initOperatorMenu();//初始化操作菜单
        showFragmentById(R.id.pmain_rbWork);//初始化显示工作这个页面resume
        clearHistoryData();//清除历史业务数据
        new Handler().postDelayed(new Runnable() {//延迟5秒发送数据到后台服务,要求后台开始执行数据上传
            @Override
            public void run() {
                TaskUtils.sendMessageToBackgroundService(context, true);
            }
        }, 5000);
    }

    /**
     * 注册退出应用的通知
     */
    public void registeExitAppReceiver(){
        exitAppReceiver = new ExitAppReceiver(new ExitAppReceiver.OnExitAppListener() {
            @Override
            public void onExitApp() {
                MainActivity.this.onExit();//退出程序
            }
        });
        IntentFilter filter = new IntentFilter(ExitAppReceiver.ACTION);
        this.registerReceiver(exitAppReceiver, filter);
    }

    /**
     * 清除历史业务数据
     */
    public synchronized void clearHistoryData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase database = dbUtils.getDatabase();
                try{
                    database.beginTransaction();
                    Calendar calendar = Calendar.getInstance(Locale.CHINA);
                    calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)
                            -SystemData.saleMan.sjbcts);
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1;
                    int day = calendar.get(Calendar.DAY_OF_MONTH);
                    String dateString = year + "-" + (month>10?month+"":"0"+month) + "-" +(day>10?day+"":"0"+day);
                    List<SaleTable> salelist = FworkDbHelper.findAllOutdateOrderlst(dbUtils,dateString);
                    if(salelist!=null && salelist.size()>0){
                        for(SaleTable item :salelist){
                            List<SaleGoodsTable> goodslist = dbUtils.findAll(Selector.from(SaleGoodsTable.class)
                                .where("xsd_id","=",item.djh));
                            if(goodslist!=null && goodslist.size()>0) dbUtils.deleteAll(goodslist);
                            List<SaleStatisticsTable> statisticslist = dbUtils.findAll(Selector.from(SaleStatisticsTable.class)
                                .where("djh","=",item.djh));
                            if(statisticslist!=null && statisticslist.size()>0) dbUtils.deleteAll(statisticslist);
                        }
                        dbUtils.deleteAll(salelist);
                    }
                    database.setTransactionSuccessful();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    database.endTransaction();
                }
            }
        }).start();
    }

    /**
     * 初始化操作菜单
     */
    public void initOperatorMenu(){
        screenWidth = PhoneUtils.getScreenInfo(this).widthPixels;
        List<OperatorMenu.OperatorItem> operatorItems = new ArrayList<OperatorMenu.OperatorItem>();
        operatorItems.add(new OperatorMenu.OperatorItem(android.R.drawable.ic_menu_add, "新增客户"));
        operatorItems.add(new OperatorMenu.OperatorItem(android.R.drawable.ic_menu_rotate, "更新客户数据"));
        operatorItems.add(new OperatorMenu.OperatorItem(android.R.drawable.ic_menu_rotate, "更新商品数据"));
        operatorMenu = new OperatorMenu(this,operatorItems);
        operatorMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://新增客户
                        addNewCustomer();//添加新客户
                        break;
                    case 1://更新客户数据
                        updateCustomerData(context);//更新客户数据
                        break;
                    case 2://更新商品数据
                        updateGoodsData(context);//更新商品数据
                        break;
                    default:
                        break;
                }
                operatorMenu.dismiss();
            }
        });
    }

    /**
     * 更新客户数据
     * @param context
     */
    public void updateCustomerData(final Context context){
        if(!NetworkUtils.isNetAvailable(context)){
            Toast.makeText(context,"当前网络不可用!",Toast.LENGTH_SHORT).show();
            return;
        }
        showDownloadTipDialog(new OnUpdateListener() {
            @Override
            public void onExecuteUpdate() {
                executeUpdateTask(context, dbUtils, new Class<?>[]{
                                ContactorTable.class,//联系人表
                                CustomerAreaTable.class,//客户地区表
                                CustomerTypeTable.class,//客户类型表
                                CustomerTable.class,//客户表
                                DeliverGoodsTable.class,//送货地址表
                                CustomerPriceTable.class,//客户价格表
                                CustomerDebtTable.class,//客户收欠款表
                                BankTable.class,//银行账户数据表
                        },
                        new int[]{5, 6, 7, 8, 9, 10, 11, 13},
                        DownloadTableActivity.methodNames);
            }
        });
    }

    /**
     * 更新商品数据
     * @param context
     */
    public void updateGoodsData(final Context context){
        if(!NetworkUtils.isNetAvailable(context)){
            Toast.makeText(context,"当前网络不可用!",Toast.LENGTH_SHORT).show();
            return;
        }
        showDownloadTipDialog(new OnUpdateListener() {
            @Override
            public void onExecuteUpdate() {
                executeUpdateTask(context, dbUtils, new Class<?>[]{
                                GoodsBrandTable.class,//品牌表
                                PriceTable.class,//价格表
                                GoodsModuleTable.class,//商品计量单位表
                                GoodsTable.class,//商品表
                                UnsoldGoodsTable.class,//未售商品列表
                                SaleBuySelfCustomerTable.class,//买赠本品客户表
                                SaleBuySelfGoodsTable.class,//买赠本品商品表
                                SaleBuySelfLevelTable.class,//买赠本品阶梯表
                                SaleBuySelfTable.class,//买赠本品表
                                SaleBuyOtherCustomerTable.class,//买赠它品客户表
                                SaleBuyOtherGiftTable.class,//买赠它品赠送表
                                SaleBuyOtherGoodsTable.class,//买赠它品商品表
                                SaleBuyOtherLevelTable.class,//买赠它品等级表
                                SaleBuyOtherTable.class,//买赠它品促销表
                                GoodsGroupTable.class,//商品分组表
                                GoodsGroupDetailTable.class,//商品分组细则表
                        },
                        new int[]{1, 2, 3, 4, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
                        DownloadTableActivity.methodNames);
            }
        });
    }

    /**
     * 显示下载数据提示
     */
    public void showDownloadTipDialog(final OnUpdateListener listener){
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("请确认网络通畅并开始更新!");
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                switch(v.getId()){
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        if(listener!=null) listener.onExecuteUpdate();
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        break;
                }
            }
        });
        msgBox.show();
    }

    /**
     * 添加新客户  1-能添加  0-不能添加
     */
    public void addNewCustomer(){
        if(SystemData.IsOperatorCustomer == 1){
            startActivity(new Intent(MainActivity.this, NewCustomerActivity.class));
            overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
        }else{
            Toast.makeText(this,"对不起，您没有操作权限!",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 执行更新数据任务
     * @param context
     * @param dbUtils
     * @param tblCls 表类名
     * @param positions 表类名在DownloadTableActivity.CHANGED_TABLES的索引值
     * @param methodNames 表类指定的下载方法数组
     */
    public void executeUpdateTask(final Context context,final DbUtils dbUtils,final Class<?>[] tblCls,final int[] positions, final String[] methodNames){
        if(positions == null || methodNames == null) return;
        new AsyncTask<Void,Integer,Void>(){
            private String errMessage = null;
            private ProgressDialog dialog = null;
            private AsyncTask task = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                TaskUtils.sendMessageToBackgroundService(context,false);//关闭后台上传服务
                task = this;//获取自己的对象
                dialog = ProgressDialog.show(context,"","正在更新数据...");
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        try{//终止当前任务
                            task.cancel(true);
                            task = null;
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Toast.makeText(context,"您取消了数据更新!",Toast.LENGTH_SHORT).show();
                        TaskUtils.sendMessageToBackgroundService(context, true);//开启后台上传服务
                    }
                });
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    for(int i=0;i<positions.length;i++) {//下载出错则跳出循环
                        if(dialog == null||task == null) break;//对话框已经被取消
                        if (!DownloadTableActivity.downloadTable(context, dbUtils
                                ,methodNames[positions[i]], positions[i],true)) {
                            errMessage = "下载出错，请重试!";
                            break;
                        }
                        publishProgress(positions.length,i+1);//传递进度至对话框
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                dialog.setMessage("已更新"+ (int)(((double)values[1]/(double)values[0])*100)+"%,请稍候...");
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                TaskUtils.sendMessageToBackgroundService(context,true);//打开后台上传服务
                if(errMessage!=null){
                    Toast.makeText(context,"更新数据出错,请检测您的网络是否畅通!",Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(context,"更新数据成功!",Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }

    /**
     * 执行手动上传单据的任务
     */
    public void executeHandleUploadTask(final Context context,final DbUtils dbUtils){
        new AsyncTask<Void,Integer,Void>(){
            private ProgressDialog dialog;
            private String errorMessage;
            private TaskConstant taskResult = TaskConstant.TASK_FAILED;
            private AsyncTask task = null;//上传任务对象

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                TaskUtils.sendMessageToBackgroundService(context, false);//关闭后台上传服务
                task = this;//任务处理对象
                dialog = ProgressDialog.show(context,"","正在上传数据，请稍候...");
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOnCancelListener(cancelListener);
            }

            /**
             * 取消参数
             */
            DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    try{
                        try{//终止当前任务
                            task.cancel(true);
                            task = null;
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Toast.makeText(context,"您取消了手动传单任务!",Toast.LENGTH_SHORT).show();
                        TaskUtils.sendMessageToBackgroundService(context, true);//开启后台上传服务
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            };

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    taskResult = TaskUtils.handleUploadAllOrders(dbUtils,new OnUploadListener() {
                        @Override
                        public void onExecuteUpload(ProgressValue progressValue) {
                            publishProgress(progressValue.executedNum,progressValue.total);
                        }
                    });
                }catch (Exception e){
                    errorMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                dialog.setMessage("已提交"+ (int)(((double)values[1]/(double)values[0])*100)+"%,请稍候...");
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                TaskUtils.sendMessageToBackgroundService(context,true);//开启后台上传服务
                if(errorMessage!=null){
                    Toast.makeText(context,"网络错误，请检测您的网络是否畅通!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(taskResult==TaskConstant.TASK_SUCCED){
                    Toast.makeText(context,"上传所有单据成功!",Toast.LENGTH_SHORT).show();
                }else if(taskResult == TaskConstant.TASK_NONE){
                    Toast.makeText(MainActivity.this,"暂时没有可上传的单据",Toast.LENGTH_SHORT).show();
                }else{
                    showUploadDialog();//显示继续上传的提示框
                }
            }
        }.execute();
    }

    /**
     * 数据处理进度值
     */
    public static class ProgressValue{
        public int total = 0;//可执行的总数
        public int executedNum = 0;//已经上传总数
        public int failedNum = 0;//上传失败总数
    }

    /**
     * 显示继续上传的提示框
     */
    public void showUploadDialog(){
        MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("上传单据出现错误，请重试!");
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch(v.getId()){
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        executeHandleUploadTask(MainActivity.this,dbUtils);
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        break;
                }
            }
        });
        msgBox.show();
    }

    /**
     * 执行手动上传数据
     */
    public void executeHandleUpload(final Context context,final DbUtils dbUtils){
        new AsyncTask<Void,Integer,Void>(){
            private ProgressDialog dialog = null;
            private String information = "";
            private boolean isHasData = false;//是否有数据要处理
            private ProgressValue progress = new ProgressValue();//进度对象

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在上传数据...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    TaskUtils.uploadAllCustomerInformation(context,dbUtils,new OnUploadListener() {
                        @Override
                        public void onExecuteUpload(ProgressValue progressValue) {
                            progress = progressValue;
                            publishProgress(0,progressValue.executedNum,progressValue.total);
                        }
                    });
                    if(progress!=null && progress.total>0){
                        isHasData = true;
                        information += "客户资料"+progress.total+"[成功"+progress.executedNum+",失败"
                                +(progress.total-progress.executedNum)+"]\n";
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
                try{
                    if(progress == null){
                        progress = new ProgressValue();//进度对象
                    }
                    progress.total = 0;
                    progress.executedNum = 0;
                    TaskUtils.uploadAllDeliverAddress(context,dbUtils,new OnUploadListener() {
                        @Override
                        public void onExecuteUpload(ProgressValue progressValue) {
                            progress = progressValue;
                            publishProgress(1,progressValue.executedNum,progressValue.total);
                        }
                    });
                    if(progress!=null && progress.total>0){
                        isHasData = true;
                        information += "送货地址"+progress.total+"[成功"+progress.executedNum+",失败"
                                +(progress.total-progress.executedNum)+"]\n";
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                try{
                    if(progress == null){
                        progress = new ProgressValue();//进度对象
                    }
                    progress.total = 0;
                    progress.executedNum = 0;
                    TaskUtils.uploadAllDeliverGoodsAddress(context,dbUtils,new OnUploadListener() {
                        @Override
                        public void onExecuteUpload(ProgressValue progressValue) {
                            progress = progressValue;
                            publishProgress(2,progressValue.executedNum,progressValue.total);
                        }
                    });
                    if(progress!=null && progress.total>0){
                        isHasData = true;
                        information += "地理位置"+progress.total+"[成功"+progress.executedNum+",失败"
                                +(progress.total-progress.executedNum)+"]\n";
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                try{
                    if(progress == null) {
                        progress = new ProgressValue();//进度对象
                    }
                    progress.total = 0;
                    progress.executedNum = 0;
                    TaskUtils.handleUploadAllOrders(dbUtils,new OnUploadListener() {
                        @Override
                        public void onExecuteUpload(ProgressValue progressValue) {
                            progress = progressValue;
                            publishProgress(3,progressValue.executedNum,progressValue.total);
                        }
                    });
                    if(progress!=null && progress.total>0){
                        isHasData = true;
                        information += "销售/订单"+progress.total+"[成功："+progress.executedNum+",失败："
                                +(progress.total-progress.executedNum)+"]";
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                String message = "";
                switch(values[0]){
                    case 0:
                        message = "客户资料";
                        break;
                    case 1:
                        message = "送货地址";
                        break;
                    case 2:
                        message = "送货地理";
                        break;
                    case 3:
                        message = "销售/订单";
                        break;
                }
                dialog.setMessage("已提交"+message+ (int)(((double)values[1]/(double)values[2])*100)+"%,请稍候...");
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                getNeedUploadCount();//计算需要上传的数据数量
                if(isHasData){
                    showMessageBox(information);
                }else{
                    Toast.makeText(MainActivity.this,"暂时没有可上传的单据",Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    /**
     * 显示消息提示框
     * @param information
     */
    private void showMessageBox(String information){
        final MessageBox msgBox = new MessageBox(context);
        msgBox.setMessage("数据提交情况：\n" + information);
        msgBox.txtCancel.setVisibility(View.GONE);
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                switch (v.getId()) {
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        break;
                }
            }
        });
        msgBox.show();
    }

    /**
     * 界面控件点击事件
     * @param v
     */
    @OnClick(value={R.id.pmain_righttop_imgMenu,R.id.pmain_txtUpload})
    public void onViewClick(View v){
        switch(v.getId()){
            case R.id.pmain_righttop_imgMenu://显示菜单
                if(operatorMenu.isShowing()){
                    operatorMenu.dismiss();
                }else {
                    operatorMenu.showAsDropDown(flHeader,screenWidth- ConstantData.TOP_MENU_WIDTH,0);
                }
            break;
            case R.id.pmain_txtUpload://上传操作
                if(!NetworkUtils.isNetAvailable(this)){
                    Toast.makeText(this,"当前网络不可用!",Toast.LENGTH_SHORT).show();
                    return;
                }
                executeHandleUpload(this,dbUtils);
            break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!SystemData.IsLogin){
            Toast.makeText(this,"您还没有登录，请先登录!",Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, LoginActivity.class));//跳转至登录页面
            this.finish();
            return;
        }
        getNeedUploadCount();//计算需要上传的数据数量
    }

    /**
     * 计算需要上传的数据数量
     */
    public void getNeedUploadCount(){
        try {
            final long count = dbUtils.count(Selector.from(SaleTable.class).where("djbz", "=", 0));
            if(count == 0){
                txtUploadCount.setVisibility(View.GONE);
            }else {
                txtUploadCount.setVisibility(View.VISIBLE);
                txtUploadCount.setText(String.valueOf(count));//当前为上传的销售单的数量
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 页面切换操作
     * @param group
     * @param checkedId
     */
    @OnRadioGroupCheckedChange(value={R.id.pmain_rgMenu})
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        showFragmentById(checkedId);//根据选择的Tab ID显示页面
    }

    /**
     * 程序退出事件
     */
    @Override
    public void onExit() {
        if(dbUtils!=null) dbUtils = null;//释放数据库操作对象
        stopService(new Intent(this, LocationService.class));
        stopService(new Intent(this, ForegroundService.class));
        this.finish();
        android.os.Process.killProcess(android.os.Process.myPid());
        android.os.Process.killProcess(android.os.Process.myTid());
        android.os.Process.killProcess(android.os.Process.myUid());
//        System.exit(0);
    }

    /**
     * 显示Fragment
     * @param cls
     * @param fragment
     * @param ft
     * @param <T>
     */
    public<T extends Fragment> void showFragment(Class<T> cls,T fragment,FragmentTransaction ft){
        try{
            if(fragment == null) {
                fragment = cls.getConstructor().newInstance();
                ft.add(R.id.pmain_flContainer,fragment,fragment.getClass()
                        .getField("TAG").get(fragment).toString());
            }else{
                ft.show(fragment);
            }
        }catch(Exception e){
            LogUtils.e("实例化Fragment错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 根据选择的Tab ID显示页面
     * @param rbId
     */
    public void showFragmentById(int rbId){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        hideAllFragment(fm, ft);//隐藏所有页面
        switch(rbId){
            case R.id.pmain_rbWork://工作页面
                showFragment(FragmentWork.class,fragmentWork,ft);
                break;
            case R.id.pmain_rbOrder://订单页面
                showFragment(FragmentReports.class,fragmentOrder,ft);
                break;
            case R.id.pmain_rbMore://更多页面
                showFragment(FragmentMore.class,fragmentMore,ft);
                break;
        }
        ft.commit();
    }

    /**
     * 隐藏所有页面
     * @param fm
     * @param ft
     */
    public void hideAllFragment(FragmentManager fm,FragmentTransaction ft){
        fragmentWork = (FragmentWork)fm.findFragmentByTag(FragmentWork.TAG);
        if(fragmentWork!=null) ft.hide(fragmentWork);
        fragmentOrder = (FragmentReports)fm.findFragmentByTag(FragmentReports.TAG);
        if(fragmentOrder!=null)ft.hide(fragmentOrder);
        fragmentMore = (FragmentMore)fm.findFragmentByTag(FragmentMore.TAG);
        if(fragmentMore!=null) ft.hide(fragmentMore);
    }

    /***
     * 按键按下事件处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
            long nowTime = System.currentTimeMillis();
            if(nowTime-exitTime>800){
                exitTime = nowTime;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                return true;
            }
            onExit();//退出程序
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if(exitAppReceiver!=null){
            this.unregisterReceiver(exitAppReceiver);
        }
        super.onDestroy();
    }
}
